package com.atguigu.gulimail.dubbo.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.service.cart_order.OrderCartDubboService;
import com.atguigu.common.service.product.ProviderProductService;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.vo.CartItem;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fangy
 * @date 2022-10-16 23:45
 */
@DubboService
public class OrderCartDubboServiceImpl implements OrderCartDubboService {


    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProviderProductService providerProductService;

    private final String CART_PREFIX = "gulimail:cart:";

    @Override
    public R getOrderItem(Long id) {

        List<CartItem> cartItem = getCartItem(CART_PREFIX + id.toString());
        List<CartItem> collect = cartItem.stream()
                .filter(item -> item.getCheck())
                .map(item -> {

                    BigDecimal skuPrice = providerProductService.getSkuPrice(item.getSkuId());
                    item.setPrice(skuPrice);

                    return item;
                })
                .collect(Collectors.toList());

        return R.ok().setData(collect);

    }

    @Override
    public R getCurrentUserCartItems(Long id) {

        List<CartItem> collect = null;

        String cartKey = CART_PREFIX + id;
        List<CartItem> cartItem = getCartItem(cartKey);
        if (cartItem == null) {
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            collect = cartItem.stream()
                    .filter((item) -> {

                        return item.getCheck();
                    })
                    .peek((item) -> {
                        BigDecimal price = providerProductService.getSkuPrice(item.getSkuId());
                        item.setPrice(price);
                    })
                    .collect(Collectors.toList());
        }

        return R.ok().setData(collect);
    }


    private List<CartItem> getCartItem(String cartKey) {

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);

        List<Object> list = operations.values();

        List<CartItem> collect = new ArrayList<>();

        if (list != null && list.size() > 0) {

            collect = list.stream().map((item) -> {

                CartItem cartItem = JSON.parseObject(item.toString(), CartItem.class);

                return cartItem;
            }).collect(Collectors.toList());

        }
        return collect;
    }

}
